<?php $modelid = $attributes['modelid'] ? $attributes['modelid'] : $param['modelid'];
//print_r($param);exit;
?>
<input type="hidden" id="<?php echo $id?>" name="<?php echo $name?>" value="<?php echo $value ? $value : (isset($_GET['parentid']) ? $_GET['parentid'] : '')?>">
<label class="hidden linkage_<?php echo $id?>">
<select name="<?php echo $name?>_linkage[]" onChange="get_linkage_<?php echo $id?>(this, this.value);">
<option value="">请选择</option>
{{each list.data as v i}}
<option value="{{v.id}}">{{v.name}}</option>
{{/each}}
</select>
</label>
<label class="linkage_<?php echo $id?>">
<?php if (isset($_GET['parentid'])){
	$models = Yii::$app->FileCache->get('backend_models_'.$modelid);
	$tablename = $models['models']['tablename'];
	$sql="SELECT depth FROM {{%$tablename}} where id = {$_GET['parentid']}";

	$category = Yii::$app->db->createCommand($sql)->queryOne();
	$category['depth'] = array_merge(explode(',', $category['depth']), [$_GET['parentid']]);
	//print_r($category['depth']);
	foreach($category['depth'] as $k=>$v){
		if ($v != $_GET['parentid']){
		    $sql="SELECT id,name FROM {{%$tablename}} where parentid = $v";
	        $categorys = Yii::$app->db->createCommand($sql)->queryAll();
		    ?>
            <select name="<?php echo $name?>_linkage[]" onChange="get_linkage_<?php echo $id?>(this, this.value);">
<option value="">请选择</option>
<?php foreach($categorys as $kk=>$vv){
	$selected = isset( $category['depth'][$k+1]) && $category['depth'][$k+1] == $vv['id'] ? ' selected' : '';
	?>
<option<?= $selected?> value="<?= $vv['id']?>"><?= $vv['name']?></option>
<?php
}
?>
</select>
            <?php
		}
	}
	?>
    
<?php
}
?>

</label>

<script>
function get_linkage_<?php echo $id?>(obj, parentid){
	if (obj){
		$(obj).nextAll().remove();
		
	}
	var div = '.linkage_<?php echo $id?>';
    var source = $(div).first().html();
	var render = template.compile(source);	
	var url = '<?php echo $this->createUrl(['mobo/models-form/get-data'])?>';
	$.getJSON(url, {modelid: '<?php echo $modelid?>',parentid: parentid || 0}, function(data){
		if (data.data.length > 0){
			var html = render({
				list: data
			});
			$(div).last().append(html);
		}
		$('input#<?php echo $id?>').val(parentid);
	});
	
}
$(function(){
	<?php if (!isset($_GET['parentid'])) {?>
	 get_linkage_<?php echo $id?>();
	 <?php
	}
	?>
	
});
</script>
